<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-row type="flex" justify="space-between">
          <el-button type="primary" @click="addCategories">添加分类</el-button>

          <el-input
            v-model="searchVal"
            placeholder="请输入关键字"
            style="width: 600px"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search" @click="searchFn" />
          </el-input>
        </el-row>
        <!-- 上面的分割线 -->
        <el-divider />
        <!-- 表格 -->
        <el-table style="width: 100%" border :data="categoriesList">
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.image" style="width: 200px; height: 200px">
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="desc" label="介绍" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="primary" @click="editFn(row)">编辑</el-button>
              <el-button type="danger" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 下面的分割线 -->
        <el-divider />
        <!-- 分页器 -->
        <el-row type="flex" justify="center">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="categoriesLength"
            :page-size="list._limit"
            current-page.sync="currentPage"
            @current-change="pageChangeFn"
          />
        </el-row>
        <!-- 弹窗 -->
        <el-dialog
          :title="categories.id ? '编辑' : '新增'"
          :visible.sync="dialogVisible"
          width="60%"
          @close="closeFn"
        >
          <el-form
            ref="form"
            label-width="80px"
            :model="categories"
            :rules="rules"
          >
            <el-form-item label="标题" prop="title">
              <el-input v-model="categories.title" />
            </el-form-item>
            <el-form-item label="描述" prop="desc">
              <el-input v-model="categories.desc" type="textarea" />
            </el-form-item>
            <el-form-item label="封面" />
            <!-- 子组件图片上传 -->
            <ImageUpload ref="myImageUpload">
              <img
                v-if="categories.id"
                alt=""
                style="width: 200px; height: 200px"
              >
            </ImageUpload>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="closeFn">取 消</el-button>
            <el-button type="primary" @click="confirm">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getCategories, addCategories, editCategories, delCategories, categoriesCount } from '@/api/categories'
import ImageUpload from './component/ImageUpload.vue'
export default {
  components: {
    ImageUpload
  },
  data() {
    return {
      currentPage: 0,
      list: {
        _limit: 3, // 获取的最大条数
        _start: 0, // 开始获取的位置
        title_contains: '' // 模糊搜索 title
      },
      categoriesLength: 0, // 分类列表的总数量
      searchVal: '', // 搜索框内容
      categoriesList: [], // 分类列表
      categories: {
        title: '',
        desc: '',
        image: ''
        // id:''
      }, // 回显
      dialogVisible: false, // 弹窗初始值
      dialog: false, // 弹窗初始值
      rules: {
        title: [
          {
            required: true,
            message: '标题不能空',
            trigger: 'blur'
          }
        ],
        desc: [
          {
            required: true,
            message: '描述不能空',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getCategoriesList()
  },
  methods: {
    // 页码变化时重新渲染页面
    pageChangeFn(data) {
      // console.log(134, data)// data就是当前的页码
      this.list._start = (data - 1) * this.list._limit
      this.getCategoriesList()
    },
    // 搜索按钮
    async searchFn() {
      // console.log(132, this.searchVal)
      // 根据搜索内容获取到当前的分类长度，有几个内容
      this.list.title_contains = this.searchVal
      this.currentPage = 0
      this.list._start = 0
      // this.categoriesLength = await categoriesCount(this.searchVal)
      console.log(134, this.categoriesLength)
      // 把搜索内容赋值给列表的模糊搜索包含属性
      // console.log(136, this.list.title_contains)
      // 更新页面，将搜索内容显示出来
      this.getCategoriesList()
    },
    // 删除分类
    delFn(id) {
      this.$confirm('此操作将永久删除是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 删除接口
          await delCategories(id)
          // 刷新页面
          this.getCategoriesList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑按钮
    editFn(data) {
      // console.log(156, data)
      this.dialogVisible = true

      this.categories.title = data.title
      this.categories.desc = data.desc

      this.$nextTick(() => {
        this.$refs.myImageUpload.fileList.push({
          url: data.image
        })
      })
    },
    // 新增分类按钮
    addCategories() {
      this.dialogVisible = true
    },
    // 确定按钮
    async confirm() {
      this.$refs.form.validate()
      if (this.categories.id) {
        // 发送编辑请求
        const res = await editCategories(this.categories)
        console.log(162, res)
      } else {
        // console.log(164, this.categories)
        // console.log('拿到子组件的图片地址', this.$refs.ImageUpload.fileList[0].url)
        this.categories.image = this.$refs.myImageUpload.fileList[0].url
        console.log(208, this.categories)
        await addCategories(this.categories)
        // console.log(126, res)
      }
      this.closeFn()
      this.getCategoriesList()
    },

    // 关闭弹窗
    closeFn() {
      this.dialogVisible = false
      this.categories = {
        title: '',
        desc: '',
        image: ''
      }
      this.$refs.form.resetFields()
      // 调用子组件的清空图片方法，防止加载上一张图片
      this.$refs.myImageUpload.onRemove()
    },
    // 获取分类列表
    async getCategoriesList() {
      // // 获取分类列表
      this.categoriesLength = await categoriesCount(this.list.title_contains)
      console.log(231, this.list)
      const res = await getCategories(this.list)
      // console.log(98, res)
      this.categoriesList = res
      // 获取到全部的分类长度，使得页面显示全部页数
      // if (!this.list.title_contains) {
      console.log(236, this.categoriesLength)
      // console.log(235, this.categoriesLength)
      // }
    }
  }
}
</script>
<style scoped>
</style>
